package com.lq;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.lq.bean.in.Hellow;
import com.lq.bean.out.ProductBody;
import com.lq.bean.out.Spec;
import com.lq.bean.out.World;

/**
 * Hello world!
 */
public class App {
    public static void main(String[] args) {
    	Collection<World> worlds = getTreeGoodsTypes();
        System.out.println(JSON.toJSON(worlds));
    }

	private static Collection<World>  getTreeGoodsTypes() {
        List<Hellow> list = getList();
        Map<String, World> typeMap = new LinkedHashMap<String, World>();
        for (Hellow hellow : list) {
        	String type = hellow.getType();
        	World world = typeMap.get(type);
        	if (world == null) {
        		world = new World(type);
        		typeMap.put(type, world);
			}
        	
        	Spec spec = new Spec(hellow.getUnit(), hellow.getSpec());
        	//先去找已存在的pd
        	ProductBody oldPb = findProductByManufacturer(world.getProducts(), hellow.getManufacturer());
        	//没有则new一个
        	if (oldPb == null) {
        		world.addProduct(new ProductBody(hellow.getManufacturer()).addSpec(spec));
			}else {
				//有则追加spec
				oldPb.addSpec(spec);
			}
        }
        
        return typeMap.values();
        
    }
    
	
	private static ProductBody findProductByManufacturer(List<ProductBody> products, String manufacturer) {
		if (products != null) {
			for (ProductBody pb : products) {
				if (manufacturer.equals(pb.getProduct())) {
					return pb;
				}
			}
		}
		return null;
	}
    
    
    

    private static List<Hellow> getList() {
        String s = "[{\"createtime\":1566303748000,\"id\":\"2c9a3b926cae6614016caefa831e000e\",\"manufacturer\":\"123\",\"ownerid\":\"1\",\"spec\":\"123\",\"type\":\"123\",\"unit\":\"123\"},{\"createtime\":1565599476000,\"id\":\"402885406c84fec6016c85002a090001\",\"manufacturer\":\"西数\",\"ownerid\":\"1\",\"spec\":\"500G\",\"type\":\"硬盘\",\"unit\":\"个\"},{\"createtime\":1565600132000,\"id\":\"402885406c850926016c850a2ee90000\",\"manufacturer\":\"华硕\",\"ownerid\":\"1\",\"spec\":\"27寸\",\"type\":\"显示器\",\"unit\":\"台\"},{\"createtime\":1565667958000,\"id\":\"402885406c88cae6016c89151e29000a\",\"manufacturer\":\"三星\",\"ownerid\":\"1\",\"spec\":\"14寸\",\"type\":\"显示器\",\"unit\":\"台\"},{\"createtime\":1565856535000,\"id\":\"402885406c941b48016c9452951c0000\",\"manufacturer\":\"三星\",\"ownerid\":\"1\",\"spec\":\"24寸\",\"type\":\"显示器\",\"unit\":\"台\"}]";
		return JSON.parseArray(s, Hellow.class);
    }
}
